package serverSide;

import static serverSide.Server.databasePassword;
import static serverSide.Server.databaseUrl;
import static serverSide.Server.databaseUser;

import static serverSide.Server.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.json.simple.JSONObject;

public class SignupController {
	static public JSONObject checkSignup(JSONObject input) {
		String username = (String)input.get(SUBJECT_SIGNUP_KEY_USERNAME);
		String password = (String)input.get(SUBJECT_SIGNUP_KEY_PASSWORD);
		
		JSONObject output = new JSONObject();
		output.put(SUBJECT_KEY, SUBJECT_VALUE_SIGNUP);												
		
		boolean isOk = false;
		
		Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
		try {
			con = DriverManager.getConnection(databaseUrl, databaseUser, databasePassword);
            pst = con.prepareStatement("INSERT INTO "+"player"+" (username,password,status) "+
            		"VALUES"+" (?,?,?);");
            pst.setString(1, username);
            pst.setString(2, password);
            pst.setInt(3, 0);
            pst.executeUpdate();
        	isOk = true;
            
        } catch (SQLException ex) {
                ex.printStackTrace();
        } finally {		
	            try {
	                if (rs != null)
	                    rs.close();
	                if (pst != null)
	                    pst.close();
	                if (con != null)
	                    con.close();
                } catch (SQLException ex) {
                	ex.printStackTrace();
	            }
	        }
		
		if(isOk)
			output.put(SUBJECT_SIGNUP_KEY_ISCREATED, SUBJECT_SIGNUP_VALUE_CREATED);
		else
			output.put(SUBJECT_SIGNUP_KEY_ISCREATED, SUBJECT_SIGNUP_VALUE_NOTCREATED);
		
		return output;
	}
}
